#!/bin/bash
# $Id: copi.funcs,v 1.3 2001/01/15 22:24:26 tom Exp $
#  ComeOn Point Functions! v0.9.2
#  - usate da vari altri moduli ComeOn Point...
#
#  AUTHOR: Beppe (beppe.dem@nsm.it)
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

HOST=`hostname`
DOMAIN=`hostname -d`
PKTNAME="ComeOn Point Installer!"
COMEONDIR=/usr/lib/ComeOn

AKASETUP=$COMEONDIR/point/.akasetup
COPIUSER=$COMEONDIR/point/.copi.user
EMSIFILE=$COMEONDIR/point/.emsi
PNTSETUP=$COMEONDIR/point/.pntsetup

mkstemp() {
  eval 'tmp_'$1'=`tempfile 2>/dev/null` || tmp_'$1'=/tmp/'$1'$$'
}

# Args: [start_uid]
# Returns: $FOUND_UID
find_unused_uid() {

  if [ $1 ]; then
    FOUND_UID=$1
  else
    FOUND_UID=501
  fi

  while [ "`cut -f3 -d: /etc/passwd | grep -x $FOUND_UID`" ]
  do
    FOUND_UID=$[$FOUND_UID+1]
  done
}

int2fido() {
 _RETVAL="`echo $1 | cut -f3 -d. | cut -c2-`:\
`echo $1 | cut -f2 -d. | cut -c2-`/\
`echo $1 | cut -f1 -d. | cut -c2-`"
}
int2fidonet() {
 _RETVAL="`echo $1 | cut -f3 -d. | cut -c2-`:\
`echo $1 | cut -f2 -d. | cut -c2-`/\
`echo $1 | cut -f1 -d. | cut -c2-`@\
`echo $1 | cut -f4- -d.`"
}
fido2int() {
 _RETVAL="f\
`echo $1 | cut -f2 -d '/'`.n\
`echo $1 | cut -f1 -d '/' | cut -f2 -d:`.z\
`echo $1 | cut -f1 -d '/' | cut -f1 -d:`"
}
fidonet2int() {
 _RETVAL="f\
`echo $1 | cut -f2 -d/ | cut -f1 -d@`.n\
`echo $1 | cut -f1 -d/ | cut -f2 -d:`.z\
`echo $1 | cut -f1 -d/ | cut -f1 -d:`.\
`echo $1 | cut -f2 -d@`"
}
fidonetpoint2int() {
 _RETVAL="p\
`echo $1 | cut -f2 -d. | cut -f1 -d@`.f\
`echo $1 | cut -f2 -d/ | cut -f1 -d.`.n\
`echo $1 | cut -f2 -d: | cut -f1 -d/`.z\
`echo $1 | cut -f1 -d/ | cut -f1 -d:`.\
`echo $1 | cut -f2 -d@`.org"
}

# Parameters: fqdn
configure_loopback() {
  vialog --backtitle "$TITLE" --infobox "Configuro la rete (in modo loopback)..." 0 0
    
  FQDN=$1
  HOST=`echo $FQDN | cut -f1 -d.`
  DOMAIN=`echo $FQDN | cut -f2- -d.`

  save /etc/hostname
  echo $FQDN >/etc/HOSTNAME
  export HOSTNAME=$FQDN
  hostname $HOST

  save /etc/rc.d/rc.inet1
  cat <<EOF >/etc/rc.d/rc.inet1 
#! /bin/sh
#
# rc.inet1      This shell script boots up the base INET system.

# Attach the loopback device.
/sbin/ifconfig lo 127.0.0.1
/sbin/route add -net 127.0.0.0

# End of rc.inet1
EOF
  chmod 755 /etc/rc.d/rc.inet1


  save /etc/networks
  cat <<EOF >/etc/networks
#
# networks      This file describes a number of netname-to-address
#               mappings for the TCP/IP subsystem.  It is mostly
#               used at boot time, when no name servers are running.
#

loopback        127.0.0.0

# End of networks.
EOF
  chmod 644 /etc/networks


  save /etc/hosts
  cat <<EOF >/etc/hosts
#
# hosts         This file describes a number of hostname-to-address
#               mappings for the TCP/IP subsystem.  It is mostly
#               used at boot time, when no name servers are running.
#               On small systems, this file can be used instead of a
#               "named" name server.  Just add the names, addresses
#               and any aliases to this file...
#
# By the way, Arnt Gulbrandsen <agulbra@nvg.unit.no> says that 127.0.0.1
# should NEVER be named with the name of the machine.  It causes problems
# for some (stupid) programs, irc and reputedly talk. :^)
#
# But we (ComeOn Linux!) says that this is not valid for you, because
# you resulted to have not a network at the installation time.

# For loopbacking.
127.0.0.1	localhost	$FQDN	$HOST

# End of hosts.
EOF
  chmod 644 /etc/hosts

  save /etc/resolv.conf
  echo domain $DOMAIN >/etc/resolv.conf
  chmod 644 /etc/resolv.conf

  save /etc/host.conf
  cat <<EOF >/etc/host.conf
order hosts,bind
multi on
EOF
  chmod 644 /etc/host.conf

  /etc/rc.d/rc.inet1
}

# Private function, adds an user to a group. Args: user, group
add_to_group() {

  if [ ! "`groups \"$1\" | grep \" $2 \"`" ]
  then
    USERS="`grep \"$2:\" /etc/group | cut -s -f4 -d:`"

    mkstemp group
    if [ "$USERS" ]; then
      sed "/$2:/s/:$USERS/:$USERS,$1/" /etc/group >$tmp_group
    else
      sed "/$2:/s/:/:$1/3" /etc/group >$tmp_group
    fi

    save /etc/group
    mv $tmp_group /etc/group
  fi
}

# Arguments: user, fullname
add_postmaster() {
  vialog --backtitle "$TITLE" --infobox "Creo l'user principale e/o ne adatto le informazioni..." 0 0

  USER="$1"
  NAME="$2"
  HOMEDIR="/home/$USER"

#  echo "$USER" >$COPIUSER	# you've to do this in any other location
  ENTRY="`cut /etc/passwd -s -f1,2,5 -d: | grep $USER:`"
  if [ "$ENTRY" ]
  then
    OLDNAME="`echo $ENTRY | cut -f3 -d:`"
    PASW="`echo $ENTRY | cut -f2 -d:`"
    if [ "$OLDNAME" != "$NAME" ]
    then
      mkstemp passwd
      sed "/$USER:$PASW:/s/:$OLDNAME:/:$NAME:/" /etc/passwd >$tmp_passwd
      save /etc/passwd
      mv $tmp_passwd /etc/passwd
    fi

    add_to_group "$USER" mail
  else
    if [ -f /bin/bash ]; then USERSHELL=/bin/bash; else USERSHELL=""; fi
    find_unused_uid
    echo "$USER:*:$FOUND_UID:12:$NAME:$HOMEDIR:$USERSHELL" >>/etc/passwd
    mkdir -p $HOMEDIR -m 755
    chown $USER.mail $HOMEDIR
  fi
}

comment_nntp_in_inetdconf() {
  vialog --backtitle "$TITLE" --infobox "Commento la riga 'nntp' in /etc/inetd.conf..." 0 0

  mkstemp inetd
  sed "/in.nntpd/s/nntp/#&/" /etc/inetd.conf >$tmp_inetd
  save /etc/inetd.conf
  mv $tmp_inetd /etc/inetd.conf
  killall -1 inetd
}

# Args: organization
set_organization() {
  vialog --backtitle "$TITLE" --infobox "Imposto l' origin..." 0 0

  ORGANIZATION=/etc/organization
  save $ORGANIZATION 

  NEW_ORGANIZATION="$1"
  echo "$NEW_ORGANIZATION" >$ORGANIZATION
}

create_innconf_newsfeeds_distrib() {
  vialog --backtitle "$TITLE" --infobox "Creo i files di configurazione principali di InterNet News (inn)..." 0 0

# File: inn.conf
  INNCONF=~news/inn.conf
  save $INNCONF

  cat <<EOF >$INNCONF
##  $Revision: 1.3 $
##  inn.conf -- inn configuration data
##  Format:
##	<parameter>:<whitespace><value>
##  Used by various programs and libinn.  The following parameters are defined:
##	domain		Local domain, without leading period.
##  	fromhost	What to put in the From line; default is FQDN
##			of the local host.
##	moderatormailer	Where to mail moderated postings, if not found
##			in the moderators file; see moderators(5).
##	pathhost	What to put in the Path and Xref headers; default
##			is FQDN of the local host.
##	organization	If $ORGANIZATION doesn't exist.  What to put in
##			the Organization header if blank.
##	server		If $NNTPSERVER doesn't exist.  Local NNTP server
##			host to connect to.
##

server:         $HOST.$DOMAIN
domain:         $DOMAIN
pathhost:	$HOST
EOF

  chmod 444 $INNCONF
  chown news.news $INNCONF


# File: newsfeeds
  NEWSFEEDS=~news/newsfeeds
  save $NEWSFEEDS

  echo -e "ME:*::\n" >$NEWSFEEDS

  IAKA=1
  OK=1
  while [ "$OK" != 0 ]
  do
    AKA="`cut $AKASETUP -f$IAKA -d:`"
    if [ ! "$AKA" ]
    then
      OK=0
    else
      if [ $IAKA != 1 ]
      then
        TMPAKA="`echo $AKA | cut -f-4 -d.`"
        SENDCRON="$SENDCRON $TMPAKA"
        echo -n "$TMPAKA/" >>$NEWSFEEDS
      fi
      TMPAKA="`echo $AKA | cut -f1-2 -d.`"
      if [ $IAKA = 1 ]; then
        SENDCRON="$SENDCRON $TMPAKA"
      fi
      echo -e "$TMPAKA\\" >>$NEWSFEEDS
      echo -e "\t:!*,`echo $AKA | cut -f4 -d.`.*\\" >>$NEWSFEEDS
      echo -e "\t:Tf,Wfb,B4096/1024:\n" >>$NEWSFEEDS
    fi
    IAKA=$[$IAKA+1]
  done

  chmod 444 $NEWSFEEDS
  chown news.news $NEWSFEEDS


# File: distrib.pats
  DISTRIB=~news/distrib.pats
  save $DISTRIB

  IAKA=1
  OK=1
  while [ "$OK" != 0 ]; do
    AKA="`cut $AKASETUP -f$IAKA -d:`"
    IAKA=$[$IAKA+1]
    if [ "$AKA" = "" ]; then
      OK=0
    else
      DOM="`echo $AKA | cut -f4 -d.`"
      echo "10:$DOM.*:$DOM" >>$DISTRIB
    fi
  done

  chmod 444 $DISTRIB
  chown news.news $DISTRIB
}

# Args: num_of_days
create_expirectl() {
  vialog --backtitle "$TITLE" --infobox "Imposto il periodo di transito dei messaggi..." 0 0

  EXPIRECTL=~news/expire.ctl
  save $EXPIRECTL

  EXPIRE_DAYS=$1

  echo -e "/remember/:14\n\n*:A:2:$EXPIRE_DAYS:$EXPIRE_DAYS" >$EXPIRECTL

  chmod 440 $EXPIRECTL
  chown news.news $EXPIRECTL
}

create_nnrpaccess() {
  vialog --backtitle "$TITLE" --infobox "Rendo accessibili le news in lettura..." 0 0

  NNRPACCESS=~news/nnrp.access
  save $NNRPACCESS

  cat <<EOF >$NNRPACCESS
##  $Revision: 1.3 $
##  nnrp.access - access file for on-campus NNTP sites
##  Format:
##	<host>:<perm>:<user>:<pass>:<groups>
##  Connecting host must be found in this file; the last match found is
##  used, so put defaults first.
##	<host>		Wildcard name or IP address
##	<perm>		R to read; P to post
##	<user>		Username for authentication before posting
##	<pass>		Password, for same reason
##	<groups>	Newsgroup patterns that can be read or not read
##  To disable posting put a space in the <user> and <pass> fields, since
##  there is no way for client to enter one.
##
## Default is no access, no way to authentication, and no groups.
# *:: -no- : -no- :!*
##  Foo, Incorporated, hosts have no password, can read anything.
# *.foo.com:Read Post:::*

*:: -no- : -no- :!*
localhost.$DOMAIN:Read Post:::*
$HOST.$DOMAIN:Read Post:::*

EOF

  chmod 440 $NNRPACCESS 
  chown news.news $NNRPACCESS 
}

create_hostsnntp() {
  vialog --backtitle "$TITLE" --infobox "Rendo accessibili le news in scrittura..." 0 0

  HOSTSNNTP=~news/hosts.nntp
  save $HOSTSNNTP

  cat <<EOF >$HOSTSNNTP
##  $Revision: 1.3 $
##  hosts.nntp - names and addresses that feed us news
##  Format
##      <host>:
##      <host>:<password>
##  <host> can be a name or IP address; no wildcards.  Any hosts not
##  listed here are handed off to nnrpd.

$HOST.$DOMAIN:

EOF
    
  chmod 440 $HOSTSNNTP
  chown news.news $HOSTSNNTP 
}

create_dirs_and_files() {

  CURMASK=`umask`
  . ./copi.wheel
  pushd /var/log >/dev/null
  mkdir -p news -m 755; chown news.news news
  cd /var/log/news; mkdir -p OLD -m 755; chown news.news OLD
  cd /var/spool; mkdir -p news -m 775; chown news.news news
  cd /var/spool/news; umask 02
  mkdir -p out.going control junk in.coming
  chown news.news out.going control junk in.coming
  cd in.coming; mkdir -p bad tmp; chown news.news bad tmp; umask $CURMASK
  ln -sf ~news /usr/local/lib/
  ln -sf ~news/inews /usr/bin/
  chmod 1777 /var/tmp

  cd /var/spool
  mkdir -p uucppublic
  chown uucp.uucp uucppublic
  chmod 1777 uucppublic

  cd ~news
  touch history history.dir history.pag errlog log
  chown news.news history* log errlog
  chmod 664 history* log errlog

  save active
  echo "control 0000000000 0000000001 y" > active
  echo "junk 0000000000 0000000001 y" >> active
  chown news.news active

  save active.times  
  echo "control 814573260 usenet" > active.times
  echo "junk 814573260 usenet" >> active.times
  chown news.news active.times

  save newsgroups
  :>newsgroups
  chown news.news newsgroups

  popd >/dev/null
}

install_rcnews() {
  vialog --backtitle "$TITLE" --infobox "Avvio l'InterNet News daemon (innd) e l'installo negli script di boot, attendere... attenzione che e' probabile che in questa fase non sia possibile entrare da un'altra VC come root." 0 0

  RCLOCAL=/etc/rc.d/rc.local
  RCNEWS=~news/etc/rc.news
  RCLINE="`grep $RCNEWS $RCLOCAL`"

  if [ ! "$RCLINE" -o `echo $RCLINE | cut -c1` = '#' ]
  then
    save $RCLOCAL
    echo -e "\n$RCNEWS" >>$RCLOCAL
  fi

  cp copi.rcnews $RCNEWS
  chmod 550 $RCNEWS
  chown news.news $RCNEWS 

  if [ -f ~news/innd/innd.pid ]; then
    su -l news -c "bin/ctlinnd shutdown x" >/dev/null
    sleep 2	# wait for server to shutdown
  fi

  killall innd 2>/dev/null	# make sure it's gone down
  $RCNEWS
}

install_crontab_news() {
  vialog --backtitle "$TITLE" --infobox "Imposto la crontab di news per l'automantenimento del sistema (cancellazione giornaliera dei messaggi vecchi et similia)..." 0 0


  if [ -f $COPIUSER ]; then
    POSTMST="`cat $COPIUSER`"
  else
    POSTMST="root"
  fi

  NEWSHOME=~news
  save /var/spool/cron/crontabs/news
  cat <<EOF | crontab - -u news
#-------------------------------------------------------------------------------
# /var/spool/cron/crontabs/news
SHELL=/bin/sh
#
MAILTO=$POSTMST
#
#===============================================================================
#
# inn-1.4 (Inter Net News)
#
#===============================================================================
#
#-------------------------------------------------------------------------------
# Daily housekeeping ... expires news and other things ...
#-------------------------------------------------------------------------------
#
51 16 * * *	$NEWSHOME/bin/news.daily < /dev/null
#
#-------------------------------------------------------------------------------
# offer spooled news - that was spooled into the incoming directory when the 
# innd server wasn't available - again to the innd server.
#-------------------------------------------------------------------------------
#
18 * * * *	$NEWSHOME/rnews -U
# 
#-------------------------------------------------------------------------------
# send news batches to your fidonet(-like) news feeds 
#-------------------------------------------------------------------------------
#
49 16 * * *	$NEWSHOME/send-ifmail$SENDCRON
#
#-------------------------------------------------------------------------------
#
EOF

  echo $NEWSHOME/send-ifmail$SENDCRON >/etc/point.ifsend
}

# Private func
# Args: dir_with_sources, bindir, cfgdir, logdir, version
copi.ifmCfg() {

  SRCDIR="$1"
  BINDIR="$2"
  CFGDIR="$3"
  LOGDIR="$4"
  VERSION="$5"
  SOURCE="$SRCDIR/CONFIG"
  CONFIGFILE="$CFGDIR/config"

  cat <<EOF >$SOURCE
# Compile-time configuration for ifmail FidoNet mailer and gateway
COPYRIGHT   = "Eugene G. Crosser, 1993-1995"
VERSION     = "$VERSION"

# Main configuration file. This default may be overwritten by -I key.
CONFIGFILE  = $CONFIGFILE

# Debug messages turned on by -x key are written here.
# Some error messages may occationally appear here too.
# This may be changed in the 'config' file.
DEBUGFILE   = "$LOGDIR/ifdebug"

# Procession log. Usually gets several lines for each invocation.
# Also look for error diagnostics here.  If HAS_SYSLOG defined,
# only stdout and stderr from the packers and unpackers go to this
# file, while actual logging is done via syslog() calls.
# This may be changed in the 'config' file.
LOGFILE     = "$LOGDIR/iflog"

# Use syslog() facility codes for mail gate, news gate and ifcico.
# Define -DHAS_SYSLOG (see below)
#MAILLOG    = LOG_MAIL
MAILLOG    = LOG_LOCAL0
#NEWSLOG    = LOG_NEWS
NEWSLOG    = LOG_LOCAL0
#CICOLOG    = LOG_UUCP
CICOLOG    = LOG_LOCAL0

# Directory where UUCP lock files reside.
#LOCKDIR     = "/var/lock"
LOCKDIR     = "/var/spool/uucp"

# Directory from which file requests are resolved.
# This may be changed from the 'config' file.
#PUBDIR      = "/home/ftp/pub"
PUBDIR      = "/var/spool/uucppublic"

# Compile-time system-dependant options. 

# If you specify "-DHAS_NDBM_H", ndbm calls will be used instead
# of dbm ones, and the feature will be activated of Cnews log processing
# to add entries to SEEN-BY if echo message is exported to several FTN
# nodes by Cnews mechanism. This works with INN too.

# If you specify "-DHAS_STATFS" or "-DHAS_STATVFS", statfs() (or statvfs()
# respectivly) call will be used to check available disk space. For statfs()
# call, you must also specify which .h file to use: "-DSTATFS_IN_VFS_H" or 
# "-DSTATFS_IN_STATFS_H" or "-DSTATFS_IN_STATVFS_H"  or "-DSTATFS_IN_MOUNT_H". 
# For statvfs() call, statvfs.h is included.

# define -DSCO_STYLE_STATFS if your statfs() call requires 4 arguments.

# If you specify "-DHAS_SETSID", setsid() call is used to detach from the
# control terminal. Otherwise setpgrp() call is used, and in this case you
# may specify "-DBSD_SETPGRP" to use BSD-style call.  Used in ifcico only.

# If you specify "-DDONT_HAVE_TM_GMTOFF", timezone offset will be calculated
# from the difference between the results of localtime() and gmtime() calls
# instead of using tm_gmtoff field of struct tm.

# If you specify "-DDONT_HAVE_GETOPT", local definitions for getopt will
# be used (but not the function itself)

# For ifcico, you must specify -DHAS_TERMIOS_H (preffered), -DHAS_TERMIO_H
# or -DHAS_SGTTY_H to use POSIX-y, SysV-ish of BSD-ish terminal control.

# in SVR4 you should specify -DHAS_DIAL (and maybe -DHAS_DIAL_H) to use
# dial() library function instead of regular open().  Lock files are
# not used in this case.

# for uucp lock files, you must specify either -DASCII_LOCKFILES or
# -DBINARY_LOCKFILES

# define -DHAS_FSYNC if there is a fsync() system call (to update .flo
# files)

# define -DPARANOID if you want iftoss to deny packets with wrong password.

# define -DRELAXED if you want iftoss to accept packets that are not
# addressed to your node.

# define -DFORCEINTL if you want ifmail to create ^aINTL even if this is
# not an inter-zone netmail.

# define -DNEED_UUCPFROM if your MTA needs a uucp "From" line in mail.

# define -DHAS_TCP if you want ifmail to be able to originate outgoing
# connections over TCP/IP (socket library needed)

# define -DHAS_TERM if you want ifmail to be able to originate outgoing
# connections over TERM (TCP "extention", client.a needed)

# define -DHAS_REGEX_H or -DHAS_LIBGEN_H if you have either of these
# header files for regular expression handlers.

# define -DHAS_SYSLOG to use syslog() instead of logging to files.
# Files are necessary anyway, external programs' stdout and stderr
# are redirected there.

# define -DNEED_BSY if you want ifpack and ifcico to create .bsy
# files preventing simultaneous processing of the same node.

# define -DNEED_FORK if your system is uncapable of getting rid of the
# control terminal unless you are running not as a group leader.

# define -DREGEX_NEED_CARET if your re_comp/re_exec require that the
# mask starts with a '^' to match the beginning of the string.

# as of June 1994, FreeBSD has a nasty bug in the kernel lseek() code:
# if you make lseek() to a point before the start of the file, it
# succeeds and the writing point becomes negative.  Fortunately, 
# subsequent write()s fail :-).  To overwork this, define 
# -DNEGATIVE_SEEK_BUG, this will add an extra fseek() to restore
# zero writing point where necessary.

# define -DNEED_TRAP if you want debugging information when the programs
# are aborted with segmentation fault etc.  Currently tested and works 
# only with Linux, and only with newer kernels (1.1.20+)

# define -DSLAVE_SENDS_NAK_TOO if you have problems answering incoming
# EMSI sessions originated by FrontDoor.  FrontDoor does not follow
# EMSI specifications when originating calls, this is a workaround.

# define -DDONT_HAVE_DIRENT if there is no working opendir()/readdir()
# etc. in your libc.  You will aso need to add "dirent.o" to the NEEDED
# (see below).

# Linux:
OPTS        = -DHAS_STATFS -DSTATFS_IN_VFS_H -DHAS_SETSID -DHAS_NDBM_H \\
		-DDONT_HAVE_TM_GMTOFF -DHAS_TERMIOS_H -DASCII_LOCKFILES \\
		-DHAS_FSYNC -DHAS_IOCTL_H -DHAS_REGEX_H -DHAS_TCP \\
		-DFORCEINTL -DHAS_SYSLOG -DNEED_UUCPFROM -DNEED_BSY \\
		-DREGEX_NEED_CARET -DNEED_TRAP -DSLAVE_SENDS_NAK_TOO \\
		-DNEED_FORK -DLESS_RFC_KLUDGES

# 386BSD:
#OPTS        = -DHAS_STATFS -DSTATFS_IN_MOUNT_H -DHAS_SETSID -DHAS_NDBM_H \\
		-DHAS_TERMIOS_H -DASCII_LOCKFILES -DHAS_FSYNC -DHAS_IOCTL_H \\
		-DHAS_REGEX_H -DHAS_TCP -DHAS_SYSLOG -DNEED_UUCPFROM \\
		-DNEED_BSY -DNEED_FORK -DNEGATIVE_SEEK_BUG \\
		-DREGEX_NEED_CARET

# SVR4:
#OPTS        = -DHAS_STATVFS -DDONT_HAVE_TM_GMTOFF -DHAS_SETSID -DHAS_NDBM_H \\
		-DHAS_TERMIOS_H -DHAS_DIAL -DHAS_DIAL_H -DASCII_LOCKFILES \\
		-DHAS_FSYNC -DHAS_IOCTL_H -DHAS_LIBGEN_H -DHAS_TCP \\
		-DHAS_SYSLOG -DREGEX_NEED_CARET
# SunOS:
#OPTS        = -DHAS_STATFS -DSTATFS_IN_VFS_H -DHAS_SETSID -DHAS_NDBM_H \\
		-DDONT_HAVE_GETOPT -DHAS_TERMIOS_H -DASCII_LOCKFILES \\
		-DHAS_FSYNC -DHAS_TCP -DHAS_SYSLOG \\
		-DREGEX_NEED_CARET

# SCO Unix 3.2v4.2
#OPTS        = -DHAS_STATFS -DSTATFS_IN_STATFS_H -DSCO_STYLE_STATFS \\
		-DHAS_TERMIOS_H -DDONT_HAVE_TM_GMTOFF -DDO_NEED_TIME \\
		-DDONT_HAVE_GETOPT -DASCII_LOCKFILES -DHAS_IOCTL_H \\
		-DHAS_TCP -DHAS_SYSLOG \\
		-DREGEX_NEED_CARET

# ISC Unix 3.2 v3.0
#OPTS        = -DHAS_STATFS -DSTATFS_IN_STATFS_H -DHAS_TERMIO_H \\
		-DDONT_HAVE_TM_GMTOFF -DDONT_HAVE_GETOPT \\
		-DASCII_LOCKFILES -DHAS_IOCTL_H -DSCO_STYLE_STATFS \\
		-DUSE_POLL -DHAS_NET_ERRNO_H -DSHORT_PID_T \\
		-DHAS_TCP -DHAS_SYSLOG \\
		-DREGEX_NEED_CARET
# On ISC, if you are suing gcc, you can run into a trouble with sscanf()
# function.  It appears that sscanf(string,"%d.%d",&int1,&int2) where
# string is a constant segfaults unless you specify "-fwritable-strings"
# to gcc.  I would say that this is a bug in ISC libc.  If nessecary,
# add this to the defines above.  If you have ISC version 4.0 or later,
# you can add "-posix", remove "-DSHORT_PID_T" and specify "-DHAS_TERMIOS"
# to get benefit of posix terminal control.

# for make install, where to put binaries and what owner to set
BINDIR = $BINDIR
OWNER = fnet
GROUP = uucp
MODE = 0711
SMODE = 4711

INSTALL = install
RANLIB = ranlib
#RANLIB = touch
SHELL = /bin/sh
ECHO = echo -e
CC = gcc
YACC = bison -y
#YACC = yacc
LEX = flex
#LEX = lex
AWK = awk
TAR = tar

#CFLAGS = -g -Wall
# Linux, 386BSD, SunOS:
CFLAGS = -O2 -Wall -m486 -s
# SVR4:
#CFLAGS = -O -Xa

LDFLAGS = -s

# For LIBS, you may need to add "-lfl" if you are using flex 2.4.x
# If you need TERM also add e.g. "/usr/src/term112/client.a"

# Linux
LIBS = -ldbm
# SunOS:
#LIBS =
# 386BSD:
#LIBS = -lgdbm -lgnuregex
# SVR4
#LIBS = -ldbm -lform -lnsl -lsocket -lc -L/usr/ucblib -lucb
# SCO
#LIBS = -ldbm -lsocket -lintl
# ISC
#LIBS = -lcposix -lmalloc -ldbm -linet -lPW

INCLUDES = -I\${INCDIR}
# ISC
#INCLUDES = -I/usr/include/rpcsvc -I\${INCDIR}

# What programs are absent at your system?
#NEEDED = strcasestr.o strncasecmp.o strcasecmp.o rename.o mkdir.o usleep.o \\
		regexpr.o
# Linux
NEEDED =
# SVR4
#NEEDED = regexpr.o
# SCO
#NEEDED = strcasestr.o strncasecmp.o strcasecmp.o usleep.o regexpr.o
# SunOS and 386BSD
#NEEDED = signal.o
# ISC
#NEEDED = usleep.o regexpr.o vsyslog.o
EOF

}

# Args: package.tgz, bin_dir, cfg_dir, log_dir, version, where_to_put_src
install_ifmail() {
  vialog --backtitle "$TITLE" --infobox "Installo e compilo Ifmail..." 0 0

  AKAPRI="`cut $AKASETUP -f1 -d:`"
  int2fido $AKAPRI
  AKAPRIFTN=$_RETVAL

  if [ -f $COPIUSER ]
  then
    POST="`cat $COPIUSER`"
  else
    POST=root
  fi

  TGZ="$1"
  BINDIR="$2"
  CFGDIR="$3"
  LOGDIR="$4"
  VERSION="$5"
  SRC="$6"

###################################################
## passwd e group
####################################

  if [ "`cut /etc/passwd -f1 -d: | grep -x fnet`" ]
  then
    mkstemp passwd
    grep -v "fnet:" /etc/passwd >$tmp_passwd
    save /etc/passwd
    mv $tmp_passwd /etc/passwd
  fi

  find_unused_uid 92
  echo "fnet:*:$FOUND_UID:14:Fidonet Gate:$BINDIR:" >>/etc/passwd


####################################################
#### dirs and files
###################################
  mkdir -p        $CFGDIR $LOGDIR /var/spool/ifmail/{BAK,nl.d} $BINDIR/magic
  chown fnet.uucp $BINDIR{,/magic} $CFGDIR $LOGDIR /var/spool/ifmail/{,BAK,nl.d}
  touch           $LOGDIR/{ifdebug,iflog,sysiflog,TheLog}
  chown fnet.uucp $LOGDIR/{ifdebug,iflog,sysiflog,TheLog}

##########################################################################
#### COMPILAZIONE
####################################

  SRC="$SRC/`tar zxvf $TGZ -C $SRC | head -1`"
# ora in $SRC c'e' il path completo dei source Ifmail

  copi.ifmCfg $SRC $BINDIR $CFGDIR $LOGDIR $VERSION
  patch -N -d $SRC <ifpatch 2>/dev/null
  make clean -C $SRC
  make -C $SRC
##########################################################################
#### INSTALLAZIONE
####################################
  make install -C $SRC
}


# Args: bin_dir, cfg_dir, log_dir, passwords
#   note: passwords are colon-separated (":")
configure_ifmail() {
  vialog --backtitle "$TITLE" --infobox "Configuro Ifmail..." 0 0

  BINDIR=$1
  CFGDIR=$2
  LOGDIR=$3
  PASSWDS=$4

  SPD="`             cut $EMSIFILE -f1`"
  SYSNAME="`         cut $EMSIFILE -f2`"
  LOCATION="`        cut $EMSIFILE -f3`"
  COMPLETE_PHONE="`  cut $EMSIFILE -f4`"
  INTERCOUNTRYPREF="`cut $EMSIFILE -f5`"
  LONG_DIST_PREFIX="`cut $EMSIFILE -f6`"
  NODEFLAGS="`       cut $EMSIFILE -f7`"
  DIALSTRING="`      cut $EMSIFILE -f8`"
  SYSOP="`           cut $EMSIFILE -f9`"

  COUNTRYPREF="`echo $COMPLETE_PHONE | cut -f1 -d'-'`"
  PREF="`       echo $COMPLETE_PHONE | cut -f2 -d'-'`"
  PHONE="`      echo $COMPLETE_PHONE | cut -f3 -d'-'`"

  FNETCFG=$CFGDIR/config
  AREAS=$CFGDIR/Areas

  POINTS="`cat $PNTSETUP`"
  POST="`cat $COPIUSER`"
  AKAPRI="`cut $AKASETUP -f1 -d:`"
  int2fido "$AKAPRI"
  AKAPRIFTN="$_RETVAL"
  
#invece di "cp $SRC/misc/inn/send-ifmail ~news"
#-----------------------------------------------------------------------------
  cp copi.sendifm1 ~news/send-ifmail
  cat <<EOF >>~news/send-ifmail
-p"$BINDIR/ifnews %s" \\
EOF
  cat copi.sendifm2 >>~news/send-ifmail

  chmod 550 ~news/send-ifmail
  chown news.news ~news/send-ifmail

#invece di "cp $SRC/misc/contrib/ifreq $BINDIR"
#-----------------------------------------------------------------------------
  cp copi.ifreq1 $BINDIR/ifreq
  cat <<EOF >>$BINDIR/ifreq
# ifcico-config-file:
\$config = "$CFGDIR/config";

# change this to the default node, where requests should go to.
\$node = "$AKAPRIFTN";
EOF
  cat copi.ifreq2 >>$BINDIR/ifreq

  chmod 755 $BINDIR/ifreq
  chown fnet.uucp $BINDIR/ifreq

#invece di "cp $SRC/misc/contrib/ifman $BINDIR"
#-----------------------------------------------------------------------------
  cp copi.ifman1 $BINDIR/ifman
  cat <<EOF >>$BINDIR/ifman
\$cfgfile="$CFGDIR/config";     # where the config is
\$ifowner="fnet";               # who is the owner of the ifmail

EOF
  cat copi.ifman2 >>$BINDIR/ifman

  chmod 755 $BINDIR/ifman
  chown fnet.uucp $BINDIR/ifman

#invece di "cp $SRC/misc/contrib/ifpoll $BINDIR"
#-----------------------------------------------------------------------------
  cp copi.ifpoll1 $BINDIR/ifpoll
  cat <<EOF >>$BINDIR/ifpoll
FIDOPATH=$BINDIR
LOGPATH=$LOGDIR

# sysop of fido stuff
IFCICO_SYSOP=$POST

# my boss node (default address to poll)
NODE=$AKAPRI
EOF
  cat copi.ifpoll2 >> $BINDIR/ifpoll

  chmod 755 $BINDIR/ifpoll
  chown fnet.uucp $BINDIR/ifpoll


#########################################################
##### se in syslog.conf non c'e' "local0.*", lo aggiunge
################################

  SYSLOG="`grep \"local0.*	\" /etc/syslog.conf`"
  SYSCHECK_A="`echo \"$SYSLOG\" | cut -f1  | grep -x \"local0.*\"`"
  SYSCHECK_B="`echo \"$SYSLOG\" | cut -f2- | grep $LOGDIR/sysiflog`"
  MYSYSLOG="local0.*\t\t\t\t\t$LOGDIR/sysiflog"

  if [ ! "$SYSCHECK_A" -o ! "$SYSCHECK_B" ]
  then
    echo -e "\n# For ifmail" >> /etc/syslog.conf
    echo -e "$MYSYSLOG" >>/etc/syslog.conf
    killall -1 syslogd
  fi


########################
  save $AREAS
  :> $AREAS
  chown fnet.uucp $AREAS

  save $FNETCFG
  cat <<EOF >$FNETCFG
# Configuration file for ifmail (ifgate+ifcico) package by Eugene Crosser
# Compile-time default name of this file may be overridden by -I key.
#
# Lines with the first nonblank character '#' are comments.
#
# Log file name. Overrides compile-time default.
logfile  $LOGDIR/iflog

# Debug file name. Overrides compile-time default.
debugfile $LOGDIR/ifdebug

# Debugging verbosity level (is overidden by -x key). Default is 0.
# WARNING: if >0 your messages will go in /tmp/ifmail !!!!!!!!!!!!!!!!!!
verbose  0

# The first is the main address:
EOF
#----------------------------

  AKA="any"
  IAKA=0
  while [ "$AKA" ]
  do
    IAKA=$[$IAKA+1]
    AKA="`cut $AKASETUP -f$IAKA -d:`"
    if [ "$AKA" ]
    then
      int2fidonet $AKA
      AKAFTN="`echo $_RETVAL | cut -f1 -d.`"
      echo "# aka for `echo $AKAFTN | cut -f2 -d '@'`" >> $FNETCFG

      POINT="`echo $POINTS | cut -f$IAKA -d:`"

      AKAFTN="`echo $AKAFTN | cut -f1 -d '@'`.$POINT@`echo $AKAFTN | cut -f2 -d '@'`"
    
      echo "address  $AKAFTN" >> $FNETCFG
    fi
  done

#----------------------------
  cat <<EOF >>$FNETCFG

# Passwords for nodes. Not checked by iftoss (unless -DPARANOID specified
# at compile-time), checked by ifcico.
# Inserted into outgoing mail packets, EMSI and yoohoo packets.
EOF
#----------------------------

  AKA="any"
  IAKA=0
  while [ "$AKA" ]
  do
    IAKA=$[$IAKA+1]
    AKA="`cut $AKASETUP -f$IAKA -d:`"
    if [ "$AKA" ]
    then
      int2fido $AKA
      AKAFTN=$_RETVAL

      PASSWD="`echo $PASSWDS | cut -f$IAKA -d:`"
      if [ "$PASSWD" ]
      then
        echo "password $AKAFTN $PASSWD" >> $FNETCFG
      fi
    fi
  done

#----------------------------
  cat <<EOF >>$FNETCFG

# Include config extention file (here: file with real passwords).
# Includes may be nested. If the nesting is cyclic, the program cycles too.
# You are warned.
# include  $CFGDIR/passwds

# System alias file - try to fetch ftn-style aliases from there.
# If "from" address of a message from FidoNet matches _right_ side
# of some entry in sysalias file, then the Reply-To: header is created
# in the RFC message with the name part taken from the left side of the
# sysalis entry and domain part taken from myfqdn (below). E.g., if a 
# fidonet message comes from "John Smith of 1:234/567.89@fidonet" and 
# there is an entry in the sysalias file:
# "jsmith: John.Smith@p89.f567.n234.z1.fidonet.org"
# and fqdn value is "pccross.msk.su", then the resulting message will
# contain a line: "Reply-To: jsmith@pccross.msk.su".
sysalias /etc/aliases

# This host fully qualified domain name to add to the alias above
myfqdn  `hostname -f`

# Directory for incoming packets/files:
inbound  /var/spool/ifmail/inb
# Directories for "listed" and "protected" sessions
listinbound /var/spool/ifmail/inb
protinbound /var/spool/ifmail/inb

# Directory for outgoing packets (default domain and zone):
# other zones will be like "/var/spool/ifmail/outb.003",
# other domains will be like "/var/spool/ifmail/<domain>.<zone>"
outbound /var/spool/ifmail/outb

# Directory from which the file requests are satisfied
public  /var/spool/uucppublic

# Directory with executables to satisfy "magic" file requests
# if requested a file present in this directory, it will be
# executed and stdout sent to the remote system. It is dangerous!
# You are warned.
magic  $BINDIR/magic

# Primary nodelist (serves "outbound" directory and domain from the
# first "address" statement). Name expanded with ".NNN" if neccessary.
nodelist /var/spool/ifmail/nl.d/`cut $AKASETUP -f1 -d: | cut -f4 -d.`.ndl

# Secondary nodelists and nodelists for other domains.
# use directory name from the first "nodelist" statement.
#           filename          originating address
EOF
#----------------------------

  AKA="any"
  IAKA=0
  while [ "$AKA" ]
  do
    IAKA=$[$IAKA+1]
    AKA="`cut $AKASETUP -f$IAKA -d:`"
    if [ "$AKA" ]
    then
      int2fidonet $AKA
      AKAFTN="`echo $_RETVAL | cut -f1 -d.`"
      echo -e "nodelist  `echo $AKAFTN | cut -f2 -d '@'`.ndl\t$AKAFTN" >> $FNETCFG
    fi
  done

#----------------------------
  cat <<EOF >>$FNETCFG

# domain translations, just context substitution.  Leading dot recommended.
# May contain '@'-sign too.  First matching used.
# NOTE: If you specify at least one domtrans line, there will be _NO_
# default for fidonet <--> fidonet.org.  Don't forget to specify it
# explicitly as a last line.
#  		FTN side  			Internet side
#domtrans	f720.n335.z2.fidonet.org	giuda.deis.unical.it
#domtrans	.fidonet			.fidonet.org

# Automatically updated alias database.  If omitted or inaccessible,
# ^aREPLYADDR and ^aREPLYTO kludges are generated in fido messages.
database	/var/spool/ifmail/ifdbm

# Sequencer file (used to generate unique IDs)
sequencer	/var/spool/ifmail/seq

# Areas file (format: "AREA newsgroup distribution")
areas		$CFGDIR/Areas

# Bad groups prefixes - do not pass to fido if appear in Newsgroups header
# This is NOT the same as "!news.group" in the cnews "sys" file.
# badgroup relcom.ads.
# badgroup relcom.commerce.

# Maximum allowed number of groups in the Newsgroups header, article will
# not be gated if exeeds.  If zero or umitted - no limit.
# maxgroup    5

# Internet -> FidoNet (outgoing) character mapping table (a la mapchan)
# outtab  $BINDIR/outkoi8alt

# FidoNet -> Internet (incoming) character mapping table
# intab  $BINDIR/outaltkoi8

# Toss program, used by ifunpack
iftoss  $BINDIR/iftoss

EOF

  cat copi.ifmcfg2 >>$FNETCFG

  if [ $[$[SPD] > $[19200]] = 1 ]; then
    SPDLOCK="L38400"
  elif [ $[$[SPD] > $[9600]] = 1 ]; then
    SPDLOCK="L19200"
  elif [ $[$[SPD] > $[2400]] = 1 ]; then
    SPDLOCK="9600"
  elif [ $[$[SPD] > $[1200]] = 1 ]; then
    SPDLOCK="2400"
  elif [ $[$[SPD] > $[300]] = 1 ]; then
    SPDLOCK="1200"
  else
    SPDLOCK="300"
  fi

  echo "ModemPort modem:$SPDLOCK" >>$FNETCFG
  cat copi.ifmcfg5 >>$FNETCFG

  echo "PhoneTrans $COUNTRYPREF-$PREF-	/" >>$FNETCFG
  echo "PhoneTrans $COUNTRYPREF-		/ $LONG_DIST_PREFIX" >>$FNETCFG
  echo "PhoneTrans		/ $INTERCOUNTRYPREF" >>$FNETCFG
  echo "ModemReset ATZ\r" >>$FNETCFG
  echo "ModemDial \d$DIALSTRING\T\r" >>$FNETCFG

  cat copi.ifmcfg4 >>$FNETCFG

  echo "Name		$SYSNAME" >>$FNETCFG
  echo "Location	$LOCATION" >>$FNETCFG
  echo "SysOp		$SYSOP" >>$FNETCFG
  echo "Phone		$COUNTRYPREF-$PREF-$PHONE" >>$FNETCFG
  echo "Speed		$SPD" >>$FNETCFG
  echo "Flags		$NODEFLAGS" >>$FNETCFG

  chown fnet.uucp $FNETCFG
}

# Args: cfg_dir
configure_smail() {
  vialog --backtitle "$TITLE" --infobox "Configuro Smail..." 0 0

  USER="`cat $COPIUSER`"
  FNETHOME=~fnet

  SMAIL=$1
  SMAILCONF=$SMAIL/config
  ALIASES=$SMAIL/aliases
  DIRECTORS=$SMAIL/directors
  ROUTERS=$SMAIL/routers
  TRANSPORTS=$SMAIL/transports
  FTNPATHS=$SMAIL/ftnpaths

# File: config
  save $SMAILCONF

  cat <<EOF >$SMAILCONF
#
#       smail configuration for $HOST.$DOMAIN
# (see smail(5) man page for details and other options)
#
hostnames=$HOST:$HOST.$DOMAIN
domains=$DOMAIN
postmaster=$USER
smtp_banner="\$primary_name Linux Smail\$version #\$compile_num ready at \$date"
spool_mode=0600
received_field="Received: \\
	\${if def:sender_host \\
		{from \$sender_host by \$primary_name \\
		\${if def:sender_proto: with \$sender_proto}\\
		\n\t(Linux Smail\$version #\$compile_num) }\\
	else{by \$primary_name \${if def:sender_proto:with \$sender_proto }\\
		(Linux Smail\$version #\$compile_num)\n\t}}\\
	id \$message_id; \$spool_date"
trusted_users=root:uucp:daemon:fnet
EOF


# File: routers
  save $ROUTERS

  cat <<EOF >$ROUTERS
ifmail: driver=pathalias,
	transport=ifmail;

	file=ftnpaths,
	proto=lsearch,
	domain=ftn:org
EOF


# File: transports
  save $TRANSPORTS

  cat <<EOF >$TRANSPORTS
local:	driver = appendfile,
	return_path,
	local,
	from,
	unix_from_hack;

	file = /var/spool/mail/\${lc:user},
	group = mail,
	mode = 0660,
	suffix = "\n",
	append_as_user

ifmail: driver=pipe,
	from,
	-received,
	max_addrs=5,
	max_chars=200;

	pipe_as_sender,
	cmd="$FNETHOME/ifmail -r\$host \$((\${strip:user})\$)"

EOF


# File: directors
  save $DIRECTORS


# File: aliases
  for i in $ALIASES /etc/aliases /usr/lib/aliases
  do
    if [ ! -L $i -a -f $i ]
    then
      mv $i $i~
    fi
  done

  USERNAME="`cut /etc/passwd -f1,5 -d: | grep $USER: | cut -f2 -d: | sed y/\" \"/./`"
  echo "news: $USER" >> $ALIASES
  echo "usenet: $USER" >> $ALIASES
  echo "$USERNAME: $USER" >> $ALIASES

  ln -sf $ALIASES /etc/
  ln -sf $ALIASES /usr/lib/

  cd $SMAIL	# is this necessary?? E-mail me if you know,please
  mkaliases >/dev/null

# File: ftnpaths
  save $FTNPATHS

  OK=1
  IAKA=1
  while [ $OK != 0 ]; do
    AKA="`cut $AKASETUP -f$IAKA -d:`"
    IAKA=$[$IAKA+1]
    if [ ! "$AKA" ]; then
      OK=0
    else
      echo -e ".`echo $AKA | cut -f4 -d.`\t\t$AKA!%s" >>$FTNPATHS
    fi
  done


# misc section

  chmod 1775 /var/spool/mail
  chgrp mail /var/spool/mail

  cd $SMAIL
  touch forward
  /usr/lib/smail/mkdbm forward

# reload sendmail
  killall sendmail 2>/dev/null
  /usr/sbin/sendmail -bd -q15m 	# if inetd handles smtp port, this will not load
}
